package com.eastedu;

import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;

import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * The type Pdf test.
 * @author zhangzhishuai
 */
public class PdfTest {


    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {
        addWaterMark("C:\\Users\\zhangzhishuai\\Desktop\\吴刚交接\\峰峰.pdf", "C:\\Users\\zhangzhishuai\\Desktop\\吴刚交接\\峰峰-1.pdf");
    }


    /**
     * 给PDF文档添加水印
     *
     * @param pdfFilePath    the pdf file path
     * @param outputFilePath the output file path
     * @author TianwYam
     */
    public static void addWaterMark(String pdfFilePath, String outputFilePath) {


        try {
            // 原PDF文件
            PdfReader reader = new PdfReader(pdfFilePath);
            // 输出的PDF文件内容
            PdfStamper stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(outputFilePath)));

            // 字体 来源于 itext-asian JAR包
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);

            PdfGState gs = new PdfGState();
            // 设置透明度
            gs.setFillOpacity(0.3f);
            gs.setStrokeOpacity(0.4f);

            int totalPage = reader.getNumberOfPages() + 1;
            for (int i = 1; i < totalPage; i++) {
                // 内容上层
			PdfContentByte content = stamper.getOverContent(i);
                // 内容下层
                /// PdfContentByte content = stamper.getUnderContent(i);

                content.beginText();
                // 字体添加透明度
                content.setGState(gs);
                // 添加字体大小等
                content.setFontAndSize(baseFont, 50);
                // 添加范围
                content.setTextMatrix(70, 200);
                // 具体位置 内容 旋转多少度 共360度
                content.showTextAligned(Element.ALIGN_CENTER, "机密文件", 300, 350, 300);
                content.showTextAligned(Element.ALIGN_TOP, "机密文件", 100, 100, 5);
                content.showTextAligned(Element.ALIGN_BOTTOM, "机密文件", 400, 400, 75);

                content.endText();
            }
            // 关闭
            stamper.close();
            reader.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}
